using Microsoft.AspNetCore.Mvc;

namespace Clear.Api.Tests.Controllers;

[Route("test")]
public class TestController : ControllerBase
{
    [HttpGet("stream")]
    public async Task TestStream([FromQuery] bool stream = false)
    {
        if (stream)
        {
            // 流式返回模式：使用分块传输，实时推送数据
            Response.ContentType = "text/event-stream"; // 或 "application/json" 配合分块
            Response.Headers.Add("Cache-Control", "no-cache");
            Response.Headers.Add("Connection", "keep-alive");
            Response.Headers.Add("X-Accel-Buffering", "no"); // 禁用代理缓冲
            Response.Headers.Remove("Content-Length"); // 关键：移除Content-Length，避免客户端等待固定长度

            // 2. 禁用ASP.NET Core自身的响应缓冲（彻底关闭缓冲）
            Response.BodyWriter.FlushAsync().GetAwaiter().GetResult();

            try
            {
                for (int i = 1; i <= 5; i++)
                {
                    // SSE格式：每行以"data:"开头，以"\n\n"结束（必须严格遵循）
                    var sseData = $"data: {{\"type\":\"stream\",\"data\":\"这是第{i}条数据\",\"index\":{i}}}\n\n";

                    // 直接写入数据，框架会自动处理分块
                    await Response.WriteAsync(sseData);

                    // 强制推送缓冲区数据（核心：确保实时发送到客户端）
                    await Response.Body.FlushAsync();

                    // 模拟处理延迟
                    await Task.Delay(1000);
                }

                // 发送结束标识
                await Response.WriteAsync("data: {\"type\":\"end\",\"data\":\"完成\"}\n\n");
                await Response.Body.FlushAsync();
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("客户端已断开连接");
            }
        }
        else
        {
            // 普通返回模式
            await Task.Delay(3000);
            await Response.WriteAsJsonAsync(new
            {
                type = "normal",
                data = "所有数据处理完成",
                total = 10
            });
        }
    }
}